<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-suffix=":">
        <el-form-item label="标题" prop="title">
          <el-input
            v-noSpace
            v-model="queryParams.title"
            placeholder="标题"
            clearable
            class="!w-[192px]"
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-select
            v-model="queryParams.status"
            class="!w-[192px]"
            clearable
            placeholder="全部"
            @change="handleQuery()"
          >
            <el-option :value="0" label="未发布" />
            <el-option :value="1" label="已发布" />
            <!-- <el-option :value="2" label="已撤回" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="消息类型" prop="msgType">
          <el-select
            v-model="queryParams.msgType"
            class="!w-[192px]"
            clearable
            placeholder="全部"
            @change="handleQuery()"
          >
            <el-option
              v-for="item in messageTypeOptions"
              :key="item.id"
              :label="item.msgType"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="消息等级" prop="msgLevel">
          <el-select
            v-model="queryParams.msgLevel"
            class="!w-[100px]"
            clearable
            placeholder="全部"
            @change="handleQuery()"
          >
            <el-option :value="0" label="低" />
            <el-option :value="1" label="中" />
            <el-option :value="2" label="高" />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
          <el-button
            type="warning"
            icon="plus"
            @click="handleOpenDialog()"
            v-hasPerm="'sys:message:edit'"
          >
            新增
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-wrapper">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        show-overflow-tooltip
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="消息标题" prop="title" max-width="100" />
        <el-table-column align="center" label="消息类型">
          <template #default="scope">
            {{ messageTypeOptions.find((item) => item.id === Number(scope.row.msgType))?.msgType }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="发布人" prop="createName" />
        <!-- <el-table-column align="center" label="消息等级">
          <template #default="scope">
            <el-tag v-if="scope.row.msgLevel == 1" type="info">低</el-tag>
            <el-tag v-if="scope.row.msgLevel == 2" type="success">中</el-tag>
            <el-tag v-if="scope.row.msgLevel == 3" type="warning">高</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="通知目标类型" prop="targetType" width="200">
          <template #default="scope">
            <el-tag v-if="scope.row.targetType == 0" type="warning">全体</el-tag>
            <div v-if="scope.row.targetType == 1">
              <!-- 显示前1个，多余的用...表示 -->
              <el-tag
                v-for="id in scope.row.targetRoleIds.split(',').slice(0, 1)"
                :key="id"
                class="mr-2"
              >
                <!-- 根据id查名字 -->
                {{ getRoleName(Number(id)) }}
              </el-tag>
              <el-tooltip
                v-if="scope.row.targetRoleIds.split(',').length > 1"
                :content="
                  scope.row.targetRoleIds
                    .split(',')
                    .slice(1)
                    .map((item: string) => getRoleName(Number(item)))
                    .join(',')
                "
              >
                <el-tag class="mr-2">...</el-tag>
              </el-tooltip>
            </div>
            <div v-if="scope.row.targetType == 2">
              <el-tag
                v-for="id in scope.row.targetUserIds.split(',').slice(0, 1)"
                :key="id"
                class="mr-2"
              >
                <!-- 根据id查名字 -->
                {{ getUserName(Number(id)) }}
              </el-tag>
              <el-tooltip
                v-if="scope.row.targetUserIds.split(',').length > 1"
                :content="
                  scope.row.targetUserIds
                    .split(',')
                    .slice(1)
                    .map((item: string) => getUserName(Number(item)))
                    .join(',')
                "
              >
                <el-tag class="mr-2">...</el-tag>
              </el-tooltip>
            </div>
            <div v-if="scope.row.targetType == 3">
              <el-tag
                v-for="role in scope.row.targetRoleIds.split(',').slice(0, 1)"
                :key="role"
                class="mr-2"
                type="success"
              >
                {{ getRoleName(Number(role)) }}
              </el-tag>
              <el-tag
                v-for="user in scope.row.targetUserIds.split(',').slice(0, 1)"
                :key="user"
                class="mr-2"
                type="success"
              >
                {{ getUserName(Number(user)) }}
              </el-tag>
              <el-tooltip
                v-if="scope.row.targetRoleIds.split(',').length > 1"
                :content="
                  scope.row.targetRoleIds
                    .split(',')
                    .slice(1)
                    .map((item: string) => getRoleName(Number(item)))
                    .join(',') +
                  ' ' +
                  scope.row.targetUserIds
                    .split(',')
                    .slice(1)
                    .map((item: string) => getUserName(Number(item)))
                    .join(',')
                "
              >
                <el-tag class="mr-2">...</el-tag>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="发布状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="info">未发布</el-tag>
            <el-tag v-if="scope.row.status == 1" type="success">已发布</el-tag>
            <!-- <el-tag v-if="scope.row.status == 2" type="warning">已撤回</el-tag> -->
          </template>
        </el-table-column>

        <el-table-column align="center" fixed="right" label="操作" min-width="150">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenNoticeDetailDialog(scope.row.id)"
            >
              查看
            </el-button>
            <el-button
              v-if="scope.row.status != 1"
              type="primary"
              size="small"
              link
              @click="handlePublish(scope.row.id)"
              v-hasPerm="'sys:message:pub'"
            >
              发布
            </el-button>
            <!-- <el-button
              v-if="scope.row.status == 1"
              type="primary"
              size="small"
              link
              @click="handleRevoke(scope.row.id)"
            >
              撤回
            </el-button> -->
            <el-button
              v-if="scope.row.status != 1"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
              v-hasPerm="'sys:message:edit'"
            >
              编辑
            </el-button>
            <el-button
              v-if="scope.row.status != 1"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
              v-hasPerm="'sys:message:del'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 消息公告表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="900"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="消息标题" prop="title">
          <el-input
            v-noSpace
            v-model="formData.title"
            placeholder="消息标题"
            maxlength="15"
            clearable
          />
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-noSpace
            v-model="formData.content"
            type="textarea"
            placeholder="消息内容"
            clearable
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="消息类型" prop="msgType">
          <!-- 选择消息类型 -->
          <el-select
            v-model="formData.msgType"
            placeholder="请选择消息类型"
            clearable
            @change="getURId"
          >
            <el-option
              v-for="item in messageTypeOptions"
              :key="item.id"
              :label="item.msgType"
              :value="item.id.toString()"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="消息等级" prop="msgLevel">
          <el-select v-model="formData.msgLevel" placeholder="请选择消息等级" clearable>
            <el-option
              v-for="item in messageLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="目标类型" prop="targetType">
          <!-- 全选 -->
          <el-checkbox v-model="formData.selectAll" @change="handleSpecifiedChange('all')">
            全选
          </el-checkbox>

          <!-- 指定角色 -->
          <el-checkbox v-model="formData.specifiedRole" @change="handleSpecifiedChange('role')">
            指定角色
          </el-checkbox>

          <!-- 指定用户 -->
          <el-checkbox v-model="formData.specifiedUser" @change="handleSpecifiedChange('user')">
            指定用户
          </el-checkbox>
        </el-form-item>

        <el-form-item
          v-if="formData.selectAll == false && formData.specifiedRole == true"
          label="指定角色"
          prop="targetRoleIds"
        >
          <el-select v-model="formData.targetRoleIds" multiple search placeholder="请选择指定角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="formData.selectAll == false && formData.specifiedUser == true"
          label="指定用户"
          prop="targetUserIds"
        >
          <el-select v-model="formData.targetUserIds" multiple search placeholder="请选择指定用户">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 消息公告详情 -->
    <NoticeDetail ref="noticeDetailRef" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Notice",
  inheritAttrs: false,
});

import messageApi, { MessagePageVO, MessageForm, MessagePageQuery } from "@/api/system/message";
import RoleAPI, { RolePageVO } from "@/api/system/role";
import UserAPI, { UserPageVO } from "@/api/system/user";
import MessageConfigAPI, { MessageConfigList } from "@/api/system/messageConfig";
import NoticeDetail from "@/layout/components/NavBar/components/NoticeDetail.vue";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const noticeDetailRef = ref();

const loading = ref(false);

const total = ref(0);

const queryParams = reactive<MessagePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const userOptions = ref<UserPageVO[]>([]);
const roleOptions = ref<RolePageVO[]>([]);

// 消息公告表格数据
const pageData = ref<MessagePageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 消息公告表单数据
const formData = reactive<
  MessageForm & { selectAll: boolean; specifiedRole: boolean; specifiedUser: boolean }
>({
  msgLevel: 0, // 默认优先级为低
  targetType: 0, // 默认目标类型为全体
  targetRoleIds: [], // 目标角色ID列表
  targetUserIds: [], // 目标用户ID列表
  id: NaN,
  title: "",
  content: "",
  msgType: null as unknown as number,
  selectAll: false,
  specifiedRole: false,
  specifiedUser: false,
});

// 获取用户名
const getUserName = (id: number) => {
  return userOptions.value.find((item) => item.id === id)?.name;
};
// 获取角色名
const getRoleName = (id: number) => {
  return roleOptions.value.find((item) => item.id === id)?.roleName;
};

// 消息公告表单校验规则
const rules = reactive({
  title: [
    { required: true, message: "请输入消息标题", trigger: "blur" },

    {
      //消息标题不能纯数字
      validator: (rule: any, value: string, callback: any) => {
        if (/^\d+$/.test(value)) {
          callback(new Error("消息标题不能纯数字"));
        } else {
          callback();
        }
      },
    },
  ],
  content: [
    {
      required: true,
      message: "请输入消息内容",
      trigger: "blur",
      validator: (rule: any, value: string, callback: any) => {
        if (!value.replace(/<[^>]+>/g, "").trim()) {
          callback(new Error("请输入消息内容"));
        } else {
          callback();
        }
      },
    },
  ],

  targetType: [{ required: true, message: "请选择目标类型", trigger: "change" }],
  targetRoleIds: [
    {
      required: true,
      message: "请选择指定角色",
      trigger: "change",
      validator: (rule: any, value: any[], callback: any) => {
        if (formData.targetType == 2 && (!value || value.length === 0)) {
          callback(new Error("请选择指定角色"));
        } else {
          callback();
        }
      },
    },
  ],
  targetUserIds: [
    {
      required: true,
      message: "请选择指定用户",
      trigger: "change",
      validator: (rule: any, value: any[], callback: any) => {
        if (formData.targetType == 3 && (!value || value.length === 0)) {
          callback(new Error("请选择指定用户"));
        } else {
          callback();
        }
      },
    },
  ],
});

// 处理选项变化
const handleSpecifiedChange = (type: "role" | "user" | "all") => {
  if (type === "all") {
    formData.selectAll = true;
    formData.specifiedRole = false;
    formData.specifiedUser = false;

    formData.targetRoleIds = [];
    formData.targetUserIds = [];
    formData.targetType = 0;
    return;
  }
  formData.selectAll = false;
};

//查询消息配置
const messageTypeOptions = ref<MessageConfigList[]>([]);
const getMessageTypeOptions = () => {
  MessageConfigAPI.getMessageConfigList({ pageNum: 1, pageSize: 999, status: 1 }).then((data) => {
    messageTypeOptions.value = data.list;
  });
};

// 查询消息公告
function handleQuery() {
  loading.value = true;
  messageApi
    .getMessageList(queryParams)
    .then((data) => {
      pageData.value = data.list;

      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 获取用户和角色选项
const getUserAndRoleOptions = () => {
  UserAPI.getPage({ pageNum: 1, pageSize: 999 }).then((data) => {
    userOptions.value = data.list;
  });
  RoleAPI.getPage({ pageNum: 1, pageSize: 999 }).then((data) => {
    roleOptions.value = data.list;
  });
};

// 打开消息公告弹窗
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改公告";
    messageApi.getMessage(id).then((data) => {
      Object.assign(formData, data);
      if (data.targetType == 0) {
        formData.specifiedRole = false;
        formData.specifiedUser = false;
        formData.selectAll = true;
      } else {
        formData.specifiedRole = data.targetRoleIds?.length > 0;
        formData.specifiedUser = data.targetUserIds?.length > 0;
        formData.selectAll = false;
      }
    });
  } else {
    dialog.title = "新增消息";
  }
}

// 获取URID
const getURId = (id: number) => {
  if (id) {
    MessageConfigAPI.getMessageConfigDetail(id).then((data) => {
      console.log(data, "data");
      formData.targetType = data.receiveType;
      formData.targetRoleIds = data.receiveRoleIds.split(",").map((item: string) => Number(item));
      formData.targetUserIds = data.receiveUserIds.split(",").map((item: string) => Number(item));
      if (formData.targetType == 0) {
        formData.specifiedRole = false;
        formData.specifiedUser = false;
        formData.selectAll = true;
      } else {
        formData.specifiedRole = data.receiveRoleIds?.length > 0;
        formData.specifiedUser = data.receiveUserIds?.length > 0;
        formData.selectAll = false;
      }
    });
  } else {
    formData.targetType = 0;
    formData.targetRoleIds = [];
    formData.targetUserIds = [];
  }
};

// 发布消息公告
function handlePublish(id: number) {
  ElMessageBox.confirm("确认发布消息?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    messageApi.publishMessage(id).then(() => {
      ElMessage.success("发布成功");
      handleQuery();
    });
  });
}

// 撤回消息公告
function handleRevoke(id: number) {
  ElMessageBox.confirm("确认撤回消息?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    messageApi.revokeMessage(id).then(() => {
      ElMessage.success("撤回成功");
      handleQuery();
    });
  });
}

// 消息公告表单提交
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (formData.selectAll) {
        formData.targetType = 0;
        formData.targetRoleIds = [];
        formData.targetUserIds = [];
      } else {
        if (formData.specifiedUser && formData.specifiedRole) {
          formData.targetType = 3;
        } else if (formData.specifiedUser) {
          formData.targetType = 2;
          formData.targetRoleIds = [];
        } else if (formData.specifiedRole) {
          formData.targetType = 1;
          formData.targetUserIds = [];
        }
      }

      if (id) {
        messageApi
          .updateMessage(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        messageApi
          .addMessage(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 重置表单
function resetForm() {
  dataFormRef.value?.resetFields();
  dataFormRef.value?.clearValidate();
  formData.id = NaN;
  formData.targetType = 0;
  formData.targetRoleIds = [];
  formData.targetUserIds = [];
  formData.selectAll = false;
  formData.specifiedRole = false;
  formData.specifiedUser = false;
}

// 关闭消息公告弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

// 删除消息公告
function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      messageApi
        .deleteMessage(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开消息公告详情弹窗
function handleOpenNoticeDetailDialog(id: number) {
  noticeDetailRef.value.openNotice(id);
}

onMounted(() => {
  handleQuery();
  getMessageTypeOptions();
  getUserAndRoleOptions();
});
onUnmounted(() => {});
</script>
<style>
.editor-wrapper {
  border: 1px solid #dcdfe6;
}
</style>
